package com.company.woye.onpackage.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.text.InputType;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.company.woye.MyApplication;
import com.company.woye.R;
import com.company.woye.base.BaseActivity;
import com.company.woye.onpackage.adapter.OnPackageDetailBoxAdapter;
import com.company.woye.onpackage.adapter.OnPackageDetailListViewAdapter;
import com.company.woye.onpackage.adapter.OnPackageDetailMaterialTypeAdapter;
import com.company.woye.onpackage.entity.AllBoxInfpEntity;
import com.company.woye.onpackage.entity.BagCallWMSEntity;
import com.company.woye.onpackage.entity.BagLoadDepartNeedEntity;
import com.company.woye.onpackage.entity.BoxDetailEntity;
import com.company.woye.onpackage.entity.BoxInfpEntity;
import com.company.woye.onpackage.entity.CallBackEntity;
import com.company.woye.onpackage.entity.InStoreEntity;
import com.company.woye.onpackage.entity.InstorCallWmsEntity;
import com.company.woye.onpackage.entity.OnPackageDetailListEntity;
import com.company.woye.onpackage.entity.OutStateEntity;
import com.company.woye.onpackage.entity.PickWallEntity;
import com.company.woye.onpackage.entity.PostBagCallWMSEntity;
import com.company.woye.onpackage.entity.PullEmptyBueEntity;
import com.company.woye.onpackage.entity.PutWallEntity;
import com.company.woye.onpackage.entity.WMSCallBackEntity;
import com.company.woye.utils.BasePopupWindow;
import com.company.woye.utils.BaseRequest;
import com.company.woye.utils.DBUtil;
import com.company.woye.utils.DataUtils;
import com.company.woye.utils.ScannerManager;
import com.company.woye.utils.SharedPreferenceUtils;
import com.company.woye.utils.Toaster;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import static android.view.View.GONE;
import static com.company.woye.utils.BaseRequest.postJsonData;

public class OnPackageDetailActivity extends BaseActivity implements OnPackageDetailListViewAdapter.State {

    @BindView(R.id.mainLinerLayout)
    LinearLayout mainLinerLayout;
    @BindView(R.id.cb_left_all)
    CheckBox cb_left_all;
    @BindView(R.id.lv_detail)
    ListView lvDetail;
    @BindView(R.id.tv_on_package_detail_deptname)
    TextView tvOnPackageDetailDeptname;
    @BindView(R.id.tv_on_package_detail_cj)
    TextView tvOnPackageDetailCj;
    @BindView(R.id.tv_on_package_detail_grop)
    TextView tvOnPackageDetailGrop;
    @BindView(R.id.tv_on_package_detail_move_number)
    TextView tvOnPackageDetailMoveNumber;
    @BindView(R.id.tv_on_package_start_time)
    TextView tvOnPackageStartTime;
    @BindView(R.id.tv_on_package_end_time)
    TextView tvOnPackageEndTime;
    @BindView(R.id.tv_on_package_detail_person)
    TextView tvOnPackageDetailPerson;
    @BindView(R.id.rb_not_verital)
    RadioButton rbNotVerital;
    @BindView(R.id.rb_verital)
    RadioButton rbVerital;
    @BindView(R.id.rg_checkout)
    RadioGroup rgCheckout;
    @BindView(R.id.edit_Barcode)
    EditText editBarcode;
    @BindView(R.id.tv_on_package_detail_box_no)
    TextView tvOnPackageDetailBoxNo;
    @BindView(R.id.tv_on_package_detail_code)
    TextView tvOnPackageDetailCode;
    @BindView(R.id.tv_on_package_detail_scan_state)
    TextView tvOnPackageDetailScanState;
    @BindView(R.id.tv_on_package_detail_other_box)
    TextView tvOnPackageDetailOtherBox;
    @BindView(R.id.tv_on_package_detail_gekou)
    TextView tvOnPackageDetailGekou;
    @BindView(R.id.tv_on_package_detail_scan_num)
    TextView tvOnPackageDetailScanNum;
    @BindView(R.id.tv_on_package_detail_box_num)
    TextView tvOnPackageDetailBoxNum;
    @BindView(R.id.cb_on_package_detail_complete)
    CheckBox cb_on_package_detail_complete;
    @BindView(R.id.tv_on_package_all_num_andout)
    TextView tv_on_package_all_num_andout;
    OnPackageDetailBoxAdapter onPackageDetailBoxAdapter;
    @BindView(R.id.lv_box_detail)
    ListView lvBoxDetail;
    @BindView(R.id.ed_on_package_heyue)
    TextView edOnPackageHeyue;
    @BindView(R.id.tv_taskStatus)
    TextView tvtaskStatus;
    @BindView(R.id.tv_taskHint)
    TextView tvtaskHint;
    @BindView(R.id.progress_task)
    ProgressBar progressTask;
    @BindView(R.id.taskLinear)
    LinearLayout taskLinear;
    @BindView(R.id.tv_taskHintClose)
    TextView tvtaskHintClose;
    @BindView(R.id.edit_zydCode)
    TextView edit_zydCode;
    @BindView(R.id.tv_on_package_detail_clearwms)
    TextView tv_on_package_detail_clearwms;


    private BasePopupWindow callPopupWindow;
    TextToSpeech textToSpeech;
    private String ZydCode = "",PortraitInfo="", dept = "", cj = "", lsx = "", start_time = "", end_time = "", LoginUserNo = "", FormType = "", Operator = "";
    private String TAG = getClass().getSimpleName();
    private JSONArray detailListJsonArray, checkBagCallWMSJsonArray, pullEmptyBusJsonArray, pullBusAwayJsonArray, pullBusAwaytransJsonArray, pullEmptyBusTransJsonArray, BagCallWMSJsonArray, BagLoadDepartNeedJsonArray,
            Check_CheckBagCallWMSJsonArray, HPBZ_AGV_Check_CheckBagCallWMS_TransJsonArray, DBAGV_Check_CheckBagCallWMSJsonArray,
            DBAGV_Check_CheckBagCallWMS_TransJsonArray, checkBagLoadDepartNeedJsonArray, instoreCallWmsJsonArry, instoreCallWmsTransJsonArry, completeJaonarray, nextTaskJsonArray, clearBoxJsonarray, waitOutJsonArray, OutJsonarray, boxJsonarray, ExceptionStateJsonArray, ALLBoxInfoJsonarray, ALLBoxDetailInfoJsonarray, zydInfoJsonArray;
    private final int MSG_FIND_DETAIL_LIST = 9000;
    private final int MSG_ERROR = 1000;
    private final int MSG_CallAgvResult = 9002;
    private final int MSG_GetBagCallWMS = 9003;
    private final int MSG_BagLoadDepartNeed = 9004;
    private final int MSG_Check_CheckBagCallWMS = 9005;
    private final int MSG_PutWallResult = 9006;
    private final int MSG_PickWallResult = 9009;
    private final int MSG_FIND_ZYDINFO = 9010;
    private final int MSG_PullEmptyBusResult = 8002;
    private final int MSG_PullAwayBusResult = 8005;
    private final int MSG_HPBZ_AGV_Check_CheckBagCallWMS = 9007;
    private final int MSG_DBAGV_Check_CheckBagCallWMS = 9008;
    private final int MSG_DBAGV_Check_CheckBagCallWMS_Trans = 8000;
    private final int MSG_pullEmptyBus = 8001;
    private final int MSG_pullEmptyBustrans = 8003;
    private final int MSG_pullBusAway = 8004;
    private final int MSG_pullBusAwaytrans = 8006;
    private final int MSG_checkBagLoadDepartNeed = 8007;
    private final int MSG_instoreCallWms = 8008;
    private final int MSG_instoreCallWms_result = 8009;
    private final int MSG_instoreCallWmsTrans = 7001;
    private final int MSG_complete = 7002;
    private final int MSG_nexttask = 7003;
    private final int MSG_clearBox = 7004;
    private final int MSG_waitOut = 7005;
    private final int MSG_waitOutCall = 7006;
    private final int MSG_ExceptionState = 7008;
    private final int MSG_ALL_BOX_INFO = 7010;
    private final int MSG_ALL_BOX_DETAIL_INFO = 7011;
    private final int MSG_BOX_DETAIL = 7012;
    private int popDelaySec = 2;
    private List<OnPackageDetailListEntity> onPackageDetailListEntities = new ArrayList<>();
    private OnPackageDetailListViewAdapter onPackageDetailListViewAdapter;
    private List<OnPackageDetailListEntity> onPackageDetailListEntityNotOutStsteList, onPackageDetailListEntityScanList;
    private String TaskID = "";
    private ScannerManager scannerManager;
    boolean ScanSign = false;
    private String IsPortrait = "0";
    private String StationNo = "";
    private List<BoxInfpEntity> boxInfpEntityList = new ArrayList<>();
    private int totalTaskCount=0,curTaskIndex=0;
    SQLiteDatabase mainDB;
    public static final String DB_Name ="bdmes.db";
    //创建数据库表
    private void CreateDBTable(){
        //打开或创建数据库文件;
        mainDB = openOrCreateDatabase(DB_Name, this.MODE_PRIVATE, null);
        if (mainDB!=null) {
            //建表语句;
            mainDB.execSQL("DROP TABLE IF EXISTS BoxOutTask");
            //员工表;
            mainDB.execSQL("CREATE TABLE IF NOT EXISTS BoxOutTask (ID INTEGER PRIMARY KEY AUTOINCREMENT,ItemIndex int,TaskID VARCHAR,OrderNo VARCHAR,BookNo VARCHAR,SiteNo VARCHAR, Priority VARCHAR," +
                    "UserNo VARCHAR,BoxNo VARCHAR,SortNo VARCHAR,BoxType VARCHAR,MainBoxNo VARCHAR,GroupValue VARCHAR)");
        }
    }
    //实现语音初始化构造函数
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (scannerManager.dispatchKeyEvent(event)) {
            return true;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        textToSpeech = new TextToSpeech(getApplicationContext(), new TTSListener());
        textToSpeech.setPitch(1.5f); // 在系统设置里也可以修改音调
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        textToSpeech.shutdown();
    }

    @Override
    public int setLayoutId() {
        return R.layout.activity_on_package_detail;
    }

    @Override
    public void initView() {
        LoginUserNo = MyApplication.curLoginUserNo;
        FormType = TAG;
        ZydCode = getIntent().getStringExtra("ZydCode");
        dept = getIntent().getStringExtra("dept");
        cj = getIntent().getStringExtra("cj");
        lsx = getIntent().getStringExtra("lsx");
        start_time = getIntent().getStringExtra("start_time");
        end_time = getIntent().getStringExtra("end_time");
        Operator = getIntent().getStringExtra("Operator");
        PortraitInfo = getIntent().getStringExtra("PortraitInfo");

        if (!TextUtils.isEmpty(PortraitInfo)) {
            edOnPackageHeyue.setText(PortraitInfo);
        }
        System.out.println(ZydCode + ";" + dept + ";" + cj + ";" + lsx + ";" + start_time + ";" + end_time);
        if (!TextUtils.isEmpty(dept)) {
            tvOnPackageDetailDeptname.setText(dept);
        }
        if (!TextUtils.isEmpty(cj)) {
            tvOnPackageDetailCj.setText(cj);
        }
        if (!TextUtils.isEmpty(lsx)) {
            tvOnPackageDetailGrop.setText(lsx);
        }
        if (!TextUtils.isEmpty(start_time)) {
            tvOnPackageStartTime.setText(start_time);
        }
        if (!TextUtils.isEmpty(end_time)) {
            tvOnPackageEndTime.setText(end_time);
        }
        if (!TextUtils.isEmpty(ZydCode)) {
            getDetail(ZydCode);
            tvOnPackageDetailMoveNumber.setText(ZydCode);
        }
        if (!TextUtils.isEmpty(Operator)) {
            tvOnPackageDetailPerson.setText(Operator);
        }

        //纵向  非纵向
        rgCheckout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.rb_not_verital) {
                    IsPortrait = "0";
                } else if (i == R.id.rb_verital) {
                    IsPortrait = "1";
                }
            }
        });
        if (((String) SharedPreferenceUtils.getData(sharedPreferences, "nowGongWei", "0")).equals("0")) {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "leftGongWei", "");
        } else {
            StationNo = (String) SharedPreferenceUtils.getData(sharedPreferences, "rightGongWei", "");
        }


        editBarcode.setInputType(InputType.TYPE_NULL);
        editBarcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                editBarcode.setInputType(InputType.TYPE_CLASS_TEXT);
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                imm.showSoftInput(editBarcode, InputMethodManager.SHOW_FORCED);
            }
        });
        editBarcode.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event != null) {
                    if ((event.getAction() == KeyEvent.ACTION_UP) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                        ScanBarcode();
                        return true;
                    }
                }
                return false;
            }
        });
        editBarcode.requestFocus();
        editBarcode.requestFocusFromTouch();
        //拦截扫描事件
        //拦截扫描事件
        scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
            @Override
            public void onResult(String code,String deviceName) {
                String nowCode = dealCode(code).trim();
                if (nowCode.indexOf("$") > -1) {
                    ZydCode = nowCode;
                    getZydInfo(ZydCode);
                    edit_zydCode.setText(ZydCode);
                } else {
                    editBarcode.setText(nowCode);
                    ScanBarcode();
                }
            }
        },editBarcode.getContext());
        mainLinerLayout = findViewById(R.id.mainLinerLayout);
        //关闭任务发送提示;
        taskLinear.setVisibility(GONE);
        CreateDBTable();


    }

    private void getZydInfo(String paramZydCode) {
        String sqlFindDept = "EXEC AGV_Check_CheckBagLoadDepartNeed @FormType='" + FormType + "',@bbm='" + dept + "',@cj_name='" + cj + "'," +
                "@lsx='" + lsx + "',@StartNeedDate='" + start_time + "',@EndNeedDate='" + end_time + "',@ZydCode='" + paramZydCode + "',@Operator=''," +
                "@OperType='GetZydInfo',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFindDept, "searchGetZydInfo");
    }

    private void ScanBarcode() {
        System.err.println("ScanBarcode-------------------------");
        boolean canScan = false;
        if (editBarcode.getText().toString().isEmpty()) {
            Toast.makeText(this, "条形码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        boolean haveNoOutStore = false;
        List<OnPackageDetailListEntity> onPackageDetailListEntityNotOutStsteList = new ArrayList<>();
        if (onPackageDetailListEntities != null && onPackageDetailListEntities.size() > 0) {
            for (int i = 0; i < onPackageDetailListEntities.size(); i++) {
                if (onPackageDetailListEntities.get(i).isCheck()) {
                    haveNoOutStore = true;
                    onPackageDetailListEntityNotOutStsteList.add(onPackageDetailListEntities.get(i));
                }
            }
            if (!haveNoOutStore) {
                Toaster.showLong(OnPackageDetailActivity.this, "请先勾选单编号");
                return;
            }
            List<String> dbhList = new ArrayList<>();
            for (int i = 0; i < onPackageDetailListEntityNotOutStsteList.size(); i++) {
                dbhList.add(onPackageDetailListEntityNotOutStsteList.get(i).getDBH());
            }
            hideIM(editBarcode);
            if (ScanSign == false) {
                ScanSign = true;
                String BoxNo = tvOnPackageDetailBoxNo.getText().toString();
                String TXM = tvOnPackageDetailCode.getText().toString();
                editBarcode.setEnabled(false);
                String SqlComm = "EXEC AGV_Check_CheckBagLoadDepartNeed @BarCode ='" + editBarcode.getText().toString()
                        + "',@DBH  ='" + DataUtils.listToString(dbhList)
                        + "',@IsPortrait='" + IsPortrait + "',@BoxNo='" + BoxNo + "',@TXM='" + TXM + "',@OutStationNo ='" + StationNo + "', @FormType='"
                        + FormType + "',@OperType='LoadScanTXM',@UserNo='" + LoginUserNo + "',@ZydCode='" + ZydCode + "',@PortraitInfo='"+PortraitInfo+"'";
                ReadSQLData(SqlComm, "Check_CheckBagLoadDepartNeed");
            } else Toast.makeText(this, "请稍等或退出重进!", Toast.LENGTH_LONG).show();
        } else {
            Toaster.showLong(OnPackageDetailActivity.this, "没有可选的单编号");
        }
    }

    @OnClick({R.id.tv_on_package_detail_clear, R.id.tv_on_package_detail_complete,
            R.id.tv_on_package_detail_next_task, R.id.tv_on_package_detail_call_in_store,
            R.id.iv_on_package_detail_back, R.id.tv_sure, R.id.tv_on_package_detail_pll_bus_away,
            R.id.tv_on_package_pull_empty_bus, R.id.tv_on_package_detail_search,
            R.id.tv_on_package_detail_call_out_store, R.id.cb_left_all,R.id.tv_taskHintClose,R.id.tv_on_package_detail_clearwms
    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_on_package_detail_clearwms:
                AlertDialog alertDialog = new AlertDialog.Builder(tvOnPackageDetailBoxNo.getContext())
                        .setTitle("系统提示").setMessage("确定要清除格口内的所有信息吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                WMSClearDpsLocation(StationNo,MyApplication.curLoginUserNo);
                                return;
                            }
                        }).create();
                alertDialog.show(); // 显示对话框
                break;
            case R.id.tv_taskHintClose:
                taskLinear.setVisibility(GONE);
                break;
            case R.id.cb_left_all:
                if (cb_left_all.isChecked()){
                    onPackageDetailListViewAdapter.allowChanged=true;
                    if (onPackageDetailListEntities != null && onPackageDetailListEntities.size() > 0) {
                        for (int i = 0; i < onPackageDetailListEntities.size(); i++) {
                            onPackageDetailListEntities.get(i).setCheck(true);
                        }
                        lvDetail.setAdapter(onPackageDetailListViewAdapter);
                    }
                }else {
                    onPackageDetailListViewAdapter.allowChanged=false;
                    if (onPackageDetailListEntities != null && onPackageDetailListEntities.size() > 0) {
                        for (int i = 0; i < onPackageDetailListEntities.size(); i++) {
                            onPackageDetailListEntities.get(i).setCheck(false);
                        }
                        lvDetail.setAdapter(onPackageDetailListViewAdapter);
                    }
                }

                break;
            case R.id.tv_sure:
                //扫描
                ScanBarcode();
                break;
            case R.id.iv_on_package_detail_back:
                finish();
                break;
            case R.id.tv_on_package_detail_pll_bus_away:
                pullBusAway();
                break;
            case R.id.tv_on_package_pull_empty_bus:
                pullEmptyBus();
                break;
            //查看详情
            case R.id.tv_on_package_detail_search:
                showPopupWindow();
                break;
            case R.id.tv_on_package_detail_call_out_store:
                //判断是否有选中待出库得
                boolean haveNoOutStore = false;
                onPackageDetailListEntityNotOutStsteList = new ArrayList<>();
                if (onPackageDetailListEntities != null && onPackageDetailListEntities.size() > 0) {
                    for (int i = 0; i < onPackageDetailListEntities.size(); i++) {
                        if (onPackageDetailListEntities.get(i).isCheck()) {
                            if (onPackageDetailListEntities.get(i).getOutState().equals("")) {
                                haveNoOutStore = true;
                                onPackageDetailListEntityNotOutStsteList.add(onPackageDetailListEntities.get(i));
                            } else {
                                haveNoOutStore = false;
                            }
                        }
                    }
                    if (!haveNoOutStore) {
                        Toaster.showLong(OnPackageDetailActivity.this, "请选择空的状态的进行出库操作");
                        return;
                    }
                    checkBagCallWMS(onPackageDetailListEntityNotOutStsteList);
                } else {
                    Toaster.showLong(OnPackageDetailActivity.this, "列表为空");
                }
                break;
            //入库
            case R.id.tv_on_package_detail_call_in_store:
                if (!TextUtils.isEmpty(tvOnPackageDetailBoxNo.getText().toString())) {
                    checkBagLoadDepartNeed(tvOnPackageDetailBoxNo.getText().toString());
                } else {
                    Toaster.showLong(OnPackageDetailActivity.this, "请先扫描箱号");
                }
                break;
            //完成
            case R.id.tv_on_package_detail_complete:
                complete();
                break;
            //下一任务
            case R.id.tv_on_package_detail_next_task:
                nextTask();
                break;
            //清空
            case R.id.tv_on_package_detail_clear:
                clearBox();
                break;
            default:
                break;
        }
    }

    //显示弹窗
    private void showWarnWindows(String paramCallInfo, String paramColor) {
        int deviationX = 300, deviationY = 300;
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        try {
            System.out.println("屏宽:" + dm.widthPixels);
            System.out.println("屏高:" + dm.heightPixels);
            //创建并初始化完成
            //创建并初始化完成
            if (callPopupWindow == null) {
                callPopupWindow = new BasePopupWindow(this);
                callPopupWindow.setWidth(dm.widthPixels - deviationX);
                callPopupWindow.setHeight(dm.heightPixels - deviationY);
            }
            //取视图
            View inflaterView = LayoutInflater.from(this).inflate(R.layout.warn_pop, null);
            LinearLayout linear_AndonPop = inflaterView.findViewById(R.id.linear_Pop);
            TextView tv_AndonPop = inflaterView.findViewById(R.id.tv_Pop);
            if (paramColor.toUpperCase().equals("RED") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_red));
            if (paramColor.toUpperCase().equals("BLUE") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_blue));
            if (paramColor.toUpperCase().equals("YELLOW") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_yellow));
            if (paramColor.toUpperCase().equals("GREEN") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_green));
            if (paramColor.toUpperCase().equals("REPEAT") == true)
                linear_AndonPop.setBackground(getResources().getDrawable(R.drawable.pop_repeat));
            tv_AndonPop.setText(paramCallInfo);
            //显示视图
            callPopupWindow.setContentView(inflaterView);
            callPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));//全透明背景
            callPopupWindow.setOutsideTouchable(false);
            callPopupWindow.setFocusable(true);
            callPopupWindow.viewSecond = popDelaySec;//显示5秒，自定义类;
            if (mainLinerLayout != null)
                callPopupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER, 0, 0);
            //发送语间播报消息;
            textToSpeech.speak(paramCallInfo, TextToSpeech.QUEUE_ADD, null);
        } catch (Exception e) {

        }

    }

    private void showPopupWindow() {
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_box_detail, null);
        final PopupWindow popupWindow = new PopupWindow(view, 1000, 800);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        ListView lv = view.findViewById(R.id.lv_detail);
        onPackageDetailBoxAdapter = new OnPackageDetailBoxAdapter(this, boxInfpEntityList);
        View view1 = LayoutInflater.from(this).inflate(R.layout.on_package_box_detail_list_group_head, null);
        lv.addHeaderView(view1);
        lv.setAdapter(onPackageDetailBoxAdapter);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        getAllBoxDetailInfo();
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    //异常
    private void exceptionState(OnPackageDetailListEntity onPackageDetailListEntity) {
        String sqlFind = "EXEC AGV_Check_CheckBagLoadDepartNeed @FormType='" + FormType + "',@OutState ='" + onPackageDetailListEntity.getOutState()
                + "',@WMSOrderNo='" + onPackageDetailListEntity.getWMSOrderNo() + "', @CurStationNo ='" + StationNo + "',@BoxNo ='',@OperType='显示异常信息',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFind, "ExceptionState");
    }

    //恢复出库
    private void Out(OnPackageDetailListEntity onPackageDetailListEntity) {
        TaskID = UUID.randomUUID().toString();
        String sqlFind = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@WMSOrderNo ='" + onPackageDetailListEntity.getWMSOrderNo() + "'" +
                ",@DBHbw='" + onPackageDetailListEntity.getDBH() + "," + onPackageDetailListEntity.getBw() + "',@TaskID ='" + TaskID + "', @FormType='" + FormType + "',@OperType='恢复出库',@UserNo='" + LoginUserNo + "' ";
        ReadSQLData(sqlFind, "Out");
    }


    //暂停出库
    private void waitOut(OnPackageDetailListEntity onPackageDetailListEntity) {
        TaskID = UUID.randomUUID().toString();
        String sqlFind = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@WMSOrderNo ='" + onPackageDetailListEntity.getWMSOrderNo() + "'" +
                ",@DBHbw='" + onPackageDetailListEntity.getDBH() + "," + onPackageDetailListEntity.getBw() + "',@TaskID ='" + TaskID + "', @FormType='" + FormType + "',@OperType='暂停出库',@UserNo='" + LoginUserNo + "' ";
        ReadSQLData(sqlFind, "waitOut");
    }

    private void waitoutWms(String ReturnInfo) {
        String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "暂停出库" + "',@TaskID='" + TaskID + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        ReadSQLData(SqlComm, "instoreCallWmsTrans");

    }

    //清空箱子
    private void clearBox() {
        String boxNo = tvOnPackageDetailBoxNo.getText().toString();
        if (!TextUtils.isEmpty(boxNo)) {
            String sqlFind = "EXEC AGV_Check_CheckBagLoadDepartNeed  @BoxNo ='" + boxNo + "', @FormType='" + FormType + "',@OperType='ClearBox',@UserNo='" + LoginUserNo + "'";
            ReadSQLData(sqlFind, "clearBox");
        } else {
            Toaster.showLong(OnPackageDetailActivity.this, "请先扫描箱码");
        }

    }

    //下一任务
    private void nextTask() {
        String sqlFind = "EXEC AGV_Check_CheckBagLoadDepartNeed  @FormType='" + FormType + "',@CurStationNo ='" + StationNo + "',@bbm='" + dept + "',@OperType='NextTask',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFind, "searchDetailList");
    }

    //完成
    private void complete() {
        String sqlFind = "EXEC AGV_Check_CheckBagLoadDepartNeed  @ZydCode ='" + ZydCode + "', @FormType='" + FormType + "',@CurStationNo ='" + StationNo + "',@OperType='SetEndState',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFind, "complete");
    }

    //入库
    private void checkBagLoadDepartNeed(String boxNo) {
        String sqlFind = "EXEC AGV_Check_CheckBagLoadDepartNeed  @BoxNo ='" + boxNo + "', @FormType='" + FormType + "',@OperType='入库',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFind, "checkBagLoadDepartNeed");
    }

    //入库返回
    private void instoreCallWms(String boxNo, String isEmpty) {
        TaskID = UUID.randomUUID().toString();
        hideIM(editBarcode);
        editBarcode.setEnabled(false);
        TaskID = UUID.randomUUID().toString();
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("OperType","入库");
            jsonObject.put("FormType",FormType);
            jsonObject.put("CurStationNo",StationNo);
            jsonObject.put("IsEmpty",isEmpty);
            jsonObject.put("BoxNo",boxNo);
            jsonObject.put("TaskID",TaskID);
            jsonObject.put("UserNo",MyApplication.curLoginUserNo);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        postJsonData(MyApplication.UrlApi + "/api/web/CheckBagCallWMS", jsonObject.toString(), handler, MSG_CallAgvResult);
    }

    private void pullEmptyBus() {
        TaskID = UUID.randomUUID().toString();
        String sqlFindDept = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "' ,@TaskID ='" + TaskID + "', @FormType='" + FormType
                + "',@OperType='拉来空车',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFindDept, "pullEmptyBus");
    }

    private void PullEmptyBusCall(String ReturnInfo) {
        String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "拉来空车" + "',@TaskID='" + TaskID + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        ReadSQLData(SqlComm, "pullEmptyBustrans");
    }

    private void pullBusAway() {
        TaskID = UUID.randomUUID().toString();
        String sqlFindDept = "  EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@BoxNo ='" + tvOnPackageDetailBoxNo.getText().toString().trim() + "',@lsx='" + lsx + "'" +
                ",@TaskID ='" + TaskID + "', @FormType='" + FormType + "',@OperType='拉走满车拉来空车',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFindDept, "pullBusAway");
    }

    private void PullAwayBusCall(String ReturnInfo) {
        String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "拉走满车拉来空车" + "',@TaskID='" + TaskID + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        ReadSQLData(SqlComm, "pullBusAwaytrans");
    }

    private void getDetail(String ZydCode) {
        String sqlFindDept = "EXEC AGV_Check_CheckBagLoadDepartNeed @FormType='" + FormType + "',@bbm='" + dept + "',@cj_name='" + cj + "'," +
                "@lsx='" + lsx + "',@StartNeedDate='" + start_time + "',@EndNeedDate='" + end_time + "',@ZydCode='" + ZydCode + "',@Operator=''," +
                "@OperType='LoadDepartNeed',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sqlFindDept, "searchDetailList");
    }

    private void refreshBoxDetail(String ZydCode, String boxNo) {
        if (boxNo!=null&&boxNo.length()>0) {
            String sqlFindDept = "EXEC AGV_Check_CheckBagGetBoxDetail @FormType='" + FormType + "',@ZydCode='" + ZydCode + "',@BoxNo='" + boxNo + "'," +
                    "@OperType='GetBoxDetail',@CurStationNo ='" + StationNo + "',@UserNo='" + LoginUserNo + "'";
            ReadSQLData(sqlFindDept, "GetBoxDetail");
        } else lvBoxDetail.setAdapter(null);
    }

    //呼叫AGV
    private void WMSClearDpsLocation(String SiteNo, String UserNo) {
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("SiteNo",SiteNo);
            jsonObject.put("UserNo",UserNo);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postJsonData(MyApplication.UrlApi+"/api/OnPackage/ClearDpsLocation",jsonObject.toString(),handler, MSG_CallAgvResult);
    }

    private void checkBagCallWMS(List<OnPackageDetailListEntity> onPackageDetailListEntityList) {
        taskLinear.setVisibility(View.VISIBLE);
        TaskID = UUID.randomUUID().toString();
        List<String> dbhList = new ArrayList<>();
        for (int i = 0; i < onPackageDetailListEntityList.size(); i++) {
            dbhList.add(onPackageDetailListEntityList.get(i).getDBH() + ","
                    + onPackageDetailListEntityList.get(i).getBw() + "," + onPackageDetailListEntityList.get(i).getOutBoxNum());
        }
        JSONObject jsonObject=new JSONObject();
        try {
            jsonObject.put("StationNo",StationNo);
            jsonObject.put("ZydCode",ZydCode);
            jsonObject.put("DBHbw",DataUtils.listToStringFenhao(dbhList));
            jsonObject.put("FormType",FormType);
            jsonObject.put("OperType","呼叫出库");
            jsonObject.put("DirType",edOnPackageHeyue.getText().toString());
            jsonObject.put("UserNo",LoginUserNo);
            jsonObject.put("TaskID",TaskID);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        System.out.println("checkBagCallWMS请求:"+MyApplication.UrlApi + "/api/OnPackage/CallBoxOut");
        System.out.println("checkBagCallWMS参数:"+jsonObject.toString());
        //直接调用呼叫接口;
        postJsonData(MyApplication.UrlApi + "/api/OnPackage/CallBoxOut", jsonObject.toString(), handler, MSG_CallAgvResult);
    }



    //花片播种
    private void Check_CheckBagCallWMS(String TXM) {
        TaskID = UUID.randomUUID().toString();
        String SqlComm = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@TaskID ='" + TaskID + "',@Zyddh ='" + ZydCode + "',@TXM ='" + TXM + "', @FormType='" + FormType + "',@OperType='花片播种',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(SqlComm, "AGV_Check_CheckBagCallWMS");
    }

    private void GetBagCallWMSTrans(String ReturnInfo, String GKH) {
        String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "花片播种" + "',@TaskID='" + TaskID + "',@GkData='" + GKH + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        ReadSQLData(SqlComm, "HPBZ_AGV_Check_CheckBagCallWMS_Trans");
    }

    //花片对包
    private void DBCheck_CheckBagCallWMS(String TXM) {
        TaskID = UUID.randomUUID().toString();
        String SqlComm = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@TaskID ='" + TaskID + "',@Zyddh ='" + ZydCode + "',@TXM ='" + TXM + "', @FormType='" + FormType + "',@OperType='花片对包拣选',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(SqlComm, "DBAGV_Check_CheckBagCallWMS");
    }

    private void DBGetBagCallWMSTrans(String ReturnInfo, String GKH) {
        String SqlComm = "Exec AGV_Check_CheckBagCallWMS_Trans  @OperType='" + "花片对包拣选" + "',@TaskID='" + TaskID + "',@GkData='" + GKH + "',@ReturnInfo='" + ReturnInfo + "',@UserNo='" + MyApplication.curLoginUserNo + "'";
        ReadSQLData(SqlComm, "DBAGV_Check_CheckBagCallWMS_Trans");
    }

    private void ReadSQLData(String sql, String type) {
        System.out.println("SQL:" + sql);
        Runnable run = new Runnable() {
            @Override
            public void run() {
                System.out.print("----存储过程:" + sql);
                try {
                    JSONArray jsonArray = DBUtil.QuerySQL2JSON(sql);
                    //
                    String OperType = "";
                    if (jsonArray!=null&&jsonArray.length()>0) {
                        if (jsonArray.optJSONObject(0).has("OperType")) {
                            OperType = jsonArray.optJSONObject(0).getString("OperType");
                        }
                    }
                    if (type.equals("GetBoxDetail")) {
                        //加载箱明细
                        boxJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_BOX_DETAIL;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    if (type.equals("searchGetZydInfo") || type.equals("GetZydInfo")) {
                        zydInfoJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_ZYDINFO;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //列表信息
                    if (type.equals("searchDetailList")) {
                        detailListJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_FIND_DETAIL_LIST;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //拉来空车
                    if (type.equals("pullEmptyBus")) {
                        pullEmptyBusJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_pullEmptyBus;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //拉来空车回调
                    if (type.equals("pullEmptyBustrans")) {
                        pullEmptyBusTransJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_pullEmptyBustrans;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //拉走满车
                    if (type.equals("pullBusAway")) {
                        pullBusAwayJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_pullBusAway;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //拉走满车回调
                    if (type.equals("pullBusAwaytrans")) {
                        pullBusAwaytransJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_pullBusAwaytrans;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //呼叫出库回调过程
                    if (type.equals("AGV_Check_CheckBagCallWMS_Trans")) {
                        BagCallWMSJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_GetBagCallWMS;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //扫码箱码 包码
                    if (type.equals("Check_CheckBagLoadDepartNeed")) {
                        BagLoadDepartNeedJsonArray = jsonArray;
                        Message msg = new Message();
                        msg.what = MSG_BagLoadDepartNeed;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //花片播种
                    if (type.equals("AGV_Check_CheckBagCallWMS")) {
                        Check_CheckBagCallWMSJsonArray = jsonArray;
                        Message msg = new Message();
                        msg.what = MSG_Check_CheckBagCallWMS;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //花片播种回调
                    if (type.equals("HPBZ_AGV_Check_CheckBagCallWMS_Trans")) {
                        HPBZ_AGV_Check_CheckBagCallWMS_TransJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_HPBZ_AGV_Check_CheckBagCallWMS;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //花片对包
                    if (type.equals("DBAGV_Check_CheckBagCallWMS")) {
                        DBAGV_Check_CheckBagCallWMSJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_DBAGV_Check_CheckBagCallWMS;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //花片对包回调
                    if (type.equals("DBAGV_Check_CheckBagCallWMS_Trans")) {
                        DBAGV_Check_CheckBagCallWMS_TransJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_DBAGV_Check_CheckBagCallWMS_Trans;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //入库
                    if (type.equals("checkBagLoadDepartNeed")) {
                        checkBagLoadDepartNeedJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_checkBagLoadDepartNeed;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //入库Callagv
                    if (type.equals("instoreCallWms")) {
                        instoreCallWmsJsonArry = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_instoreCallWms;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //入库Callagv回调
                    if (type.equals("instoreCallWmsTrans")) {
                        instoreCallWmsTransJsonArry = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_instoreCallWmsTrans;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //完成
                    if (type.equals("complete")) {
                        completeJaonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_complete;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //下一任务
                    if (type.equals("nextTask")) {
                        nextTaskJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_nexttask;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //清空
                    if (type.equals("clearBox")) {
                        clearBoxJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_clearBox;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //暂停出库
                    if (type.equals("waitOut")) {
                        waitOutJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_waitOut;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }

                    //点击列表异常状态
                    if (type.equals("ExceptionState")) {
                        ExceptionStateJsonArray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_ExceptionState;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //获取箱信息
                    if (type.equals("MSG_ALL_BOX_INFO")) {
                        ALLBoxInfoJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_ALL_BOX_INFO;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                    //查看明细
                    if (type.equals("MSG_ALL_BOX_DETAIL_INFO")) {
                        ALLBoxDetailInfoJsonarray = jsonArray;
                        //刷新界面;
                        Message msg = new Message();
                        msg.what = MSG_ALL_BOX_DETAIL_INFO;
                        handler.removeMessages(msg.what);
                        handler.sendMessage(msg);
                        return;
                    }
                } catch (Exception e) {
                    Message msg = new Message();
                    msg.what = MSG_ERROR;
                    handler.removeMessages(msg.what);
                    handler.sendMessage(msg);
                    e.printStackTrace();
                    System.out.print(e.toString());
                }

            }

        };
        new Thread(run).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //刷新包状态
            String boxNo = tvOnPackageDetailBoxNo.getText().toString();
            switch (msg.what) {
                //箱明细
                case MSG_BOX_DETAIL:
                    if (boxJsonarray != null & boxJsonarray.length() > 0) {
                        Log.e("11111", "箱明细");
                        Gson gson = new Gson();
                        List<BoxDetailEntity> onPackageDetailListEntities = gson.fromJson(String.valueOf(boxJsonarray), new TypeToken<List<BoxDetailEntity>>() {
                        }.getType());
                        lvBoxDetail.setAdapter(new OnPackageDetailMaterialTypeAdapter(OnPackageDetailActivity.this, onPackageDetailListEntities));
                    }
                    break;
                case MSG_ERROR:
                    Toaster.showLong(OnPackageDetailActivity.this, "未返回任何数据");
                    break;
                case MSG_FIND_ZYDINFO:
                    if (zydInfoJsonArray != null & zydInfoJsonArray.length() > 0) {
                        try {
                            if (zydInfoJsonArray.optJSONObject(0).has("ErrInfo")) {
                                AlertDialog alertDialog = null; // 创建对话框
                                try {
                                    alertDialog = new AlertDialog.Builder(tvOnPackageDetailBoxNo.getContext())
                                            .setTitle("系统提示").setMessage(zydInfoJsonArray.getJSONObject(0).getString("ErrInfo"))
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int which) {
                                                    return;
                                                }
                                            }).create();
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                alertDialog.show(); // 显示对话框
                                lvDetail.setAdapter(null);
                                lvBoxDetail.setAdapter(null);
                            }
                            if (zydInfoJsonArray.optJSONObject(0).has("ZydCode"))
                                ZydCode = zydInfoJsonArray.optJSONObject(0).getString("ZydCode");
                            if (zydInfoJsonArray.optJSONObject(0).has("dept"))
                                dept = zydInfoJsonArray.optJSONObject(0).getString("dept");
                            if (zydInfoJsonArray.optJSONObject(0).has("cj"))
                                cj = zydInfoJsonArray.optJSONObject(0).getString("cj");
                            if (zydInfoJsonArray.optJSONObject(0).has("lsx"))
                                lsx = zydInfoJsonArray.optJSONObject(0).getString("lsx");
                            if (zydInfoJsonArray.optJSONObject(0).has("start_time"))
                                start_time = zydInfoJsonArray.optJSONObject(0).getString("start_time");
                            if (zydInfoJsonArray.optJSONObject(0).has("end_time"))
                                end_time = zydInfoJsonArray.optJSONObject(0).getString("end_time");
                            if (zydInfoJsonArray.optJSONObject(0).has("PortraitInfo"))
                                PortraitInfo = zydInfoJsonArray.optJSONObject(0).getString("PortraitInfo");
                            if (!TextUtils.isEmpty(dept)) {
                                tvOnPackageDetailDeptname.setText(dept);
                            }
                            if (!TextUtils.isEmpty(cj)) {
                                tvOnPackageDetailCj.setText(cj);
                            }
                            if (!TextUtils.isEmpty(lsx)) {
                                tvOnPackageDetailGrop.setText(lsx);
                            }
                            if (!TextUtils.isEmpty(start_time)) {
                                tvOnPackageStartTime.setText(start_time);
                            }
                            if (!TextUtils.isEmpty(end_time)) {
                                tvOnPackageEndTime.setText(end_time);
                            }
                            if (!TextUtils.isEmpty(ZydCode)) {
                                getDetail(ZydCode);
                                tvOnPackageDetailMoveNumber.setText(ZydCode);
                            }
                            if (!TextUtils.isEmpty(PortraitInfo)) {
                                edOnPackageHeyue.setText(PortraitInfo);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                    break;
                //获取列表
                case MSG_FIND_DETAIL_LIST:
                    if (detailListJsonArray != null && detailListJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        onPackageDetailListEntities = gson.fromJson(String.valueOf(detailListJsonArray), new TypeToken<List<OnPackageDetailListEntity>>() {
                        }.getType());
                        onPackageDetailListViewAdapter = new OnPackageDetailListViewAdapter(OnPackageDetailActivity.this, onPackageDetailListEntities, OnPackageDetailActivity.this);
                        lvDetail.setAdapter(onPackageDetailListViewAdapter);
                        Toaster.showLong(OnPackageDetailActivity.this, "获取成功");

                        String dept = onPackageDetailListEntities.get(0).getExtBbm();
                        String cj = onPackageDetailListEntities.get(0).getCj_name();
                        String lsx = onPackageDetailListEntities.get(0).getLsx();
                        String start_time = onPackageDetailListEntities.get(0).getsBNeedDate();
                        String end_time = onPackageDetailListEntities.get(0).getsENeedDate();
                        String ZydCode = onPackageDetailListEntities.get(0).getZydbh();
                        if (!TextUtils.isEmpty(dept)) {
                            tvOnPackageDetailDeptname.setText(dept);
                        }
                        if (!TextUtils.isEmpty(cj)) {
                            tvOnPackageDetailCj.setText(cj);
                        }
                        if (!TextUtils.isEmpty(lsx)) {
                            tvOnPackageDetailGrop.setText(lsx);
                        }
                        if (!TextUtils.isEmpty(start_time)) {
                            tvOnPackageStartTime.setText(start_time);
                        }
                        if (!TextUtils.isEmpty(end_time)) {
                            tvOnPackageEndTime.setText(end_time);
                        }
                        if (!TextUtils.isEmpty(ZydCode)) {
                            // getDetail(ZydCode);
                            tvOnPackageDetailMoveNumber.setText(ZydCode);
                        }

                    } else{
                        lvDetail.setAdapter(null);
                        lvBoxDetail.setAdapter(null);
                        Toaster.showLong(OnPackageDetailActivity.this,"未找到单编号对应明细数据");
                    }
                    break;
                //呼叫出库回调
                case MSG_CallAgvResult:
                    String tmpstr=msg.obj.toString();
                    System.out.println("MSG_CallAgvResult:"+tmpstr);
                    try {
                        JSONObject jsonObject=new JSONObject(tmpstr);
                        if (jsonObject.has("status")&&jsonObject.has("errorinfo")){
                            tvOnPackageDetailOtherBox.setText(jsonObject.getString("errorinfo"));
                            if (jsonObject.getInt("status")==0)
                                tvOnPackageDetailOtherBox.setTextColor(getResources().getColor(R.color.green));
                            else
                                tvOnPackageDetailOtherBox.setTextColor(getResources().getColor(R.color.red));
                            if (jsonObject.getString("errorinfo")!=null&&jsonObject.getString("errorinfo").length()>0){
                                Toaster.showLong(OnPackageDetailActivity.this,jsonObject.getString("errorinfo"));
                            }
                        } else{
                            tvtaskHint.setText(msg.obj.toString());
                        }
                        if (jsonObject.has("data")&&jsonObject.get("data")!=null){
                            String data=jsonObject.getString("data");
                            System.out.println("data:"+data);
                            if (data.length()>0&&data.equals("null")==false) {
                                JSONArray jsonArray = new JSONArray(data);
                                if (jsonArray != null && jsonArray.length() > 0) {
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        JSONObject object = jsonArray.getJSONObject(i);
                                        if (object.has("BookNo") && object.has("ResultInfo")&&object.has("BoxNos")) {
                                            tvtaskHint.setText(object.getString("BookNo") + ":" + object.getString("BoxNos")+"-"+ object.getString("ResultInfo")
                                                    + "\r\n" + tvtaskHint.getText().toString());
                                        }else if (object.has("BookNo") && object.has("ResultInfo")) {
                                            tvtaskHint.setText(object.getString("BookNo") +"-"+ object.getString("ResultInfo")
                                                    + "\r\n" + tvtaskHint.getText().toString());
                                        }
                                    }
                                }
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;
                case MSG_GetBagCallWMS:
                    if (BagCallWMSJsonArray != null && BagCallWMSJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(BagCallWMSJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                        ///刷新总箱数
                        getAllBoxInfo();
                        //刷新包状态
                        refreshBoxDetail(ZydCode, boxNo);
                    }
                    break;
                //扫描箱子码  包码
                case MSG_BagLoadDepartNeed:
                    ScanSign = false;
                    editBarcode.setEnabled(true);
                    System.out.println("BagLoadDepartNeedJsonArray:" + BagLoadDepartNeedJsonArray);
                    if (BagLoadDepartNeedJsonArray != null && BagLoadDepartNeedJsonArray.length() > 0) {
                        if (BagLoadDepartNeedJsonArray.optJSONObject(0).has("ErrInfo")) {
                            AlertDialog alertDialog = null; // 创建对话框
                            try {
                                alertDialog = new AlertDialog.Builder(tvOnPackageDetailBoxNo.getContext())
                                        .setTitle("系统提示").setMessage(BagLoadDepartNeedJsonArray.getJSONObject(0).getString("ErrInfo"))
                                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog, int which) {
                                                return;
                                            }
                                        }).create();
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            alertDialog.show(); // 显示对话框
                        }
                        System.out.println("BagLoadDepartNeedJsonArray:1");
                        Gson gson = new Gson();
                        List<BagLoadDepartNeedEntity> BagLoadDepartNeedEntitys = gson.fromJson(String.valueOf(BagLoadDepartNeedJsonArray), new TypeToken<List<BagLoadDepartNeedEntity>>() {
                        }.getType());
                        System.out.println("BagLoadDepartNeedJsonArray:2");
                        if (BagLoadDepartNeedEntitys != null && BagLoadDepartNeedEntitys.size() > 0) {
                            boxNo = BagLoadDepartNeedEntitys.get(0).getBoxNo();
                            if (!TextUtils.isEmpty(boxNo)) {
                                tvOnPackageDetailBoxNo.setText(boxNo);
                            }
                            System.out.println("BagLoadDepartNeedJsonArray:3");
                            String TXM = BagLoadDepartNeedEntitys.get(0).getTXM();
                            if (!TextUtils.isEmpty(TXM)) {
                                tvOnPackageDetailCode.setText(TXM);
                            }
                            System.out.println("BagLoadDepartNeedJsonArray:4");
                            String InBoxNum = BagLoadDepartNeedEntitys.get(0).getInBoxNum();
                            if (!TextUtils.isEmpty(InBoxNum)) {
                                tvOnPackageDetailBoxNum.setText(InBoxNum);
                            }
                            System.out.println("BagLoadDepartNeedJsonArray:5");
                            String ScanNum = BagLoadDepartNeedEntitys.get(0).getScanNum();
                            if (!TextUtils.isEmpty(ScanNum)) {
                                tvOnPackageDetailScanNum.setText(ScanNum);
                            }
                            System.out.println("BagLoadDepartNeedJsonArray:6");
                            String OutState = BagLoadDepartNeedEntitys.get(0).getOutState();
                            if (!TextUtils.isEmpty(OutState)) {
                                tvOnPackageDetailScanState.setText(OutState);
                                tvOnPackageDetailScanState.setTextColor(GetColorValue(BagLoadDepartNeedEntitys.get(0).getFontColor()));
                            }
                            if (!TextUtils.isEmpty(BagLoadDepartNeedEntitys.get(0).getResultInfo())) {
                                tvOnPackageDetailOtherBox.setText(BagLoadDepartNeedEntitys.get(0).getResultInfo());
                            }
                            System.out.println("BagLoadDepartNeedJsonArray:7");
                            //1,判断outstate =Y的时候再继续判断   isPieceNo isCrossNo
                            //2,isPieceNo=1的时候 调用花片播种  isCrossNo=1的时候调用
                            if (!TextUtils.isEmpty(BagLoadDepartNeedEntitys.get(0).getOutState())) {
                                if (BagLoadDepartNeedEntitys.get(0).getOutState().equals("Y")) {
                                    boolean needrefresh=true;
                                    //花片播种
                                    if (!TextUtils.isEmpty(BagLoadDepartNeedEntitys.get(0).getIsPieceNo()) && BagLoadDepartNeedEntitys.get(0).getIsPieceNo().equals("1")) {
                                        System.out.println("BagLoadDepartNeedJsonArray:Check_CheckBagCallWMS before");
                                        Check_CheckBagCallWMS(BagLoadDepartNeedEntitys.get(0).getTXM());
                                        needrefresh=false;
                                    }
                                    //花片对包拣选
                                    if (!TextUtils.isEmpty(BagLoadDepartNeedEntitys.get(0).getIsCrossNo()) && BagLoadDepartNeedEntitys.get(0).getIsCrossNo().equals("1")) {
                                        System.out.println("BagLoadDepartNeedJsonArray:DBCheck_CheckBagCallWMS before");
                                        DBCheck_CheckBagCallWMS(BagLoadDepartNeedEntitys.get(0).getTXM());
                                        needrefresh=false;
                                    }
                                    if (needrefresh==true) refreshBoxDetail(ZydCode, boxNo);
                                } else  refreshBoxDetail(ZydCode, boxNo);
                            } else  refreshBoxDetail(ZydCode, boxNo);
                            System.out.println("BagLoadDepartNeedJsonArray:8");
                            if (!TextUtils.isEmpty(BagLoadDepartNeedEntitys.get(0).getCardInfo())) {
                                if (BagLoadDepartNeedEntitys.get(0).getCardDelay() > 0)
                                    popDelaySec = BagLoadDepartNeedEntitys.get(0).getCardDelay();
                                if (BagLoadDepartNeedEntitys.get(0).getCardInfo().length() > 0)
                                    showWarnWindows(BagLoadDepartNeedEntitys.get(0).getCardInfo(), BagLoadDepartNeedEntitys.get(0).getCardColor());
                            }

                        }
                    }
                    break;
                //调用花片播种WMS
                case MSG_Check_CheckBagCallWMS:
                    if (Check_CheckBagCallWMSJsonArray != null && Check_CheckBagCallWMSJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<PutWallEntity> check_checkBagCallWMSEntities = gson.fromJson(String.valueOf(Check_CheckBagCallWMSJsonArray), new TypeToken<List<PutWallEntity>>() {
                        }.getType());
                        if (check_checkBagCallWMSEntities != null && check_checkBagCallWMSEntities.size() > 0) {
                            if (!TextUtils.isEmpty(check_checkBagCallWMSEntities.get(0).getResultInfo()) && !TextUtils.isEmpty(check_checkBagCallWMSEntities.get(0).getFontColor())) {
                                tvOnPackageDetailOtherBox.setText(check_checkBagCallWMSEntities.get(0).getResultInfo());
                                tvOnPackageDetailOtherBox.setTextColor(GetColorValue(check_checkBagCallWMSEntities.get(0).getFontColor()));
                            } else {
                                //调用WMS
                                PutWall(check_checkBagCallWMSEntities);
                            }

                        }
                    }
                    refreshBoxDetail(ZydCode, boxNo);
                    break;
                //花片播种回调
                case MSG_PutWallResult:
                    System.out.println("MSG_PutWallResult：" + msg.obj.toString());
                    System.out.println("MSG:" + msg);
                    if (msg.arg1 == BaseRequest.HAND_REQUEST_SUCCESS) {
                        Gson gson2 = new Gson();
                        List<String> list = new ArrayList<>();
                        WMSCallBackEntity wmsCallBackEntity2 = gson2.fromJson(msg.obj.toString(), WMSCallBackEntity.class);
                        if (wmsCallBackEntity2.getStatus().equals("0")) {
                            if (wmsCallBackEntity2.getData() != null && wmsCallBackEntity2.getData().size() > 0) {
                                for (int i = 0; i < wmsCallBackEntity2.getData().size(); i++) {
                                    list.add(wmsCallBackEntity2.getData().get(i));
                                }
                            }
                        }
                        Toaster.showLong(OnPackageDetailActivity.this, wmsCallBackEntity2.getErrorinfo());
                        if (list != null && list.size() > 0) {
                            GetBagCallWMSTrans(msg.obj.toString(), DataUtils.listToString(list));
                            tvOnPackageDetailGekou.setText(DataUtils.listToString(list));
                        } else {
                            GetBagCallWMSTrans(msg.obj.toString(), "");
                        }
                    } else {
                        GetBagCallWMSTrans(msg.obj.toString(), "");
                    }
                    break;
                //花片播种回调返回
                case MSG_HPBZ_AGV_Check_CheckBagCallWMS:
                    if (HPBZ_AGV_Check_CheckBagCallWMS_TransJsonArray != null && HPBZ_AGV_Check_CheckBagCallWMS_TransJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(HPBZ_AGV_Check_CheckBagCallWMS_TransJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }

                    break;
                //调用花片对包
                case MSG_DBAGV_Check_CheckBagCallWMS:
                    if (DBAGV_Check_CheckBagCallWMSJsonArray != null && DBAGV_Check_CheckBagCallWMSJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<PickWallEntity> check_checkBagCallWMSEntities = gson.fromJson(String.valueOf(DBAGV_Check_CheckBagCallWMSJsonArray), new TypeToken<List<PickWallEntity>>() {
                        }.getType());
                        if (check_checkBagCallWMSEntities != null && check_checkBagCallWMSEntities.size() > 0) {
                            if (!TextUtils.isEmpty(check_checkBagCallWMSEntities.get(0).getResultInfo()) && !TextUtils.isEmpty(check_checkBagCallWMSEntities.get(0).getFontColor())) {
                                tvOnPackageDetailOtherBox.setText(check_checkBagCallWMSEntities.get(0).getResultInfo());
                                tvOnPackageDetailOtherBox.setTextColor(GetColorValue(check_checkBagCallWMSEntities.get(0).getFontColor()));
                            } else {
                                //调用WMS
                                PickWall(check_checkBagCallWMSEntities);
                            }

                        }
                    }
                    refreshBoxDetail(ZydCode, boxNo);
                    break;
                //调用花片对包回调
                case MSG_PickWallResult:
                    System.out.println("MSG_PickWallResult：" + msg.obj.toString());
                    if (msg.arg1 == BaseRequest.HAND_REQUEST_SUCCESS) {
                        Gson gson3 = new Gson();
                        WMSCallBackEntity wmsCallBackEntity3 = gson3.fromJson(msg.obj.toString(), WMSCallBackEntity.class);
                        List<String> list1 = new ArrayList<>();
                        if (wmsCallBackEntity3.getStatus().equals("0")) {
                            if (wmsCallBackEntity3.getData() != null && wmsCallBackEntity3.getData().size() > 0) {
                                for (int i = 0; i < wmsCallBackEntity3.getData().size(); i++) {
                                    list1.add(wmsCallBackEntity3.getData().get(i));
                                }
                            }
                        }
                        Toaster.showLong(OnPackageDetailActivity.this, wmsCallBackEntity3.getErrorinfo());
                        if (list1 != null && list1.size() > 0) {
                            DBGetBagCallWMSTrans(msg.obj.toString(), DataUtils.listToString(list1));
                            tvOnPackageDetailGekou.setText(DataUtils.listToString(list1));
                        } else {
                            DBGetBagCallWMSTrans(msg.obj.toString(), "");
                        }
                    } else {
                        DBGetBagCallWMSTrans(msg.obj.toString(), "");
                    }

                    break;
                //调用花片对包回调返回
                case MSG_DBAGV_Check_CheckBagCallWMS_Trans:
                    if (DBAGV_Check_CheckBagCallWMS_TransJsonArray != null && DBAGV_Check_CheckBagCallWMS_TransJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(DBAGV_Check_CheckBagCallWMS_TransJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }
                    break;
                //拉来空车
                case MSG_pullEmptyBus:
                    if (pullEmptyBusJsonArray != null && pullEmptyBusJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<PullEmptyBueEntity> putWallEntities = gson.fromJson(String.valueOf(pullEmptyBusJsonArray), new TypeToken<List<PullEmptyBueEntity>>() {
                        }.getType());
                        getPullEmptyBusWMS(putWallEntities);
                    }
                    break;
                //拉来空车回调
                case MSG_PullEmptyBusResult:
                    PullEmptyBusCall(msg.obj.toString());
                    break;
                //拉来空车回调返回
                case MSG_pullEmptyBustrans:
                    if (pullEmptyBusTransJsonArray != null && pullEmptyBusTransJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(pullEmptyBusTransJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }
                    break;
                //拉走满车  拉来空车
                case MSG_pullBusAway:
                    if (pullBusAwayJsonArray != null && pullBusAwayJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<PullEmptyBueEntity> putWallEntities = gson.fromJson(String.valueOf(pullBusAwayJsonArray), new TypeToken<List<PullEmptyBueEntity>>() {
                        }.getType());
                        getPullAwayBusWMS(putWallEntities);
                    }
                    break;
                case MSG_PullAwayBusResult:
                    PullAwayBusCall(msg.obj.toString());
                    break;
                case MSG_pullBusAwaytrans:
                    if (pullBusAwaytransJsonArray != null && pullBusAwaytransJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(pullBusAwaytransJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }
                    break;
                //入库
                case MSG_checkBagLoadDepartNeed:
                    if (checkBagLoadDepartNeedJsonArray != null && checkBagLoadDepartNeedJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<InStoreEntity> inStoreEntities = gson.fromJson(String.valueOf(checkBagLoadDepartNeedJsonArray), new TypeToken<List<InStoreEntity>>() {
                        }.getType());
                        if (inStoreEntities != null && inStoreEntities.size() > 0) {
                            if (!TextUtils.isEmpty(inStoreEntities.get(0).getResultInfo()) && !TextUtils.isEmpty(inStoreEntities.get(0).getFontColor())) {
                                tvOnPackageDetailOtherBox.setText(inStoreEntities.get(0).getResultInfo());
                                tvOnPackageDetailOtherBox.setTextColor(GetColorValue(inStoreEntities.get(0).getFontColor()));
                            } else {
                                if (inStoreEntities.get(0).getIsHaveTxm().equals("N")) {
                                    //N空箱入库
                                    showChooseBox(inStoreEntities.get(0).getBoxNo());
                                } else if (inStoreEntities.get(0).getIsHaveTxm().equals("Y")) {
                                    //非空箱入库
                                    instoreCallWms(inStoreEntities.get(0).getBoxNo(), "2");
                                }
                            }

                        }
                    }
                    break;
                //入库callWMS
                case MSG_instoreCallWms:
                    if (instoreCallWmsJsonArry != null && instoreCallWmsJsonArry.length() > 0) {
                        Gson gson = new Gson();
                        List<InstorCallWmsEntity> instorCallWmsEntities = gson.fromJson(String.valueOf(instoreCallWmsJsonArry),
                                new TypeToken<List<InstorCallWmsEntity>>() {
                                }.getType());
                        if (instorCallWmsEntities != null && instorCallWmsEntities.size() > 0) {
                            if (!TextUtils.isEmpty(instorCallWmsEntities.get(0).getResultInfo()) && !TextUtils.isEmpty(instorCallWmsEntities.get(0).getFontColor())) {
                                tvOnPackageDetailOtherBox.setText(instorCallWmsEntities.get(0).getResultInfo());
                                tvOnPackageDetailOtherBox.setTextColor(GetColorValue(instorCallWmsEntities.get(0).getFontColor()));
                            } else {
                                //呼叫WMS
                                instorecallWms(instorCallWmsEntities.get(0));
                            }
                        }
                    }
                    break;
                //完成
                case MSG_complete:
                    if (completeJaonarray != null && completeJaonarray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(completeJaonarray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                        if (cb_on_package_detail_complete.isChecked()) {
                            pullBusAway();
                        }
                    }
                    break;
                //下一任务
                case MSG_nexttask:
                    if (nextTaskJsonArray != null && nextTaskJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(nextTaskJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }
                    break;
                //清空
                case MSG_clearBox:
                    if (clearBoxJsonarray != null && clearBoxJsonarray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> CallBackEntity = gson.fromJson(String.valueOf(clearBoxJsonarray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        Toaster.showLong(OnPackageDetailActivity.this, CallBackEntity.get(0).getResultInfo());
                    }
                    break;
                case MSG_waitOut:
                    if (waitOutJsonArray != null && waitOutJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<OutStateEntity> CallBackEntity = gson.fromJson(String.valueOf(waitOutJsonArray), new TypeToken<List<OutStateEntity>>() {
                        }.getType());

                        if (CallBackEntity != null && CallBackEntity.size() > 0) {
                            if (!TextUtils.isEmpty(CallBackEntity.get(0).getResultInfo()) && !TextUtils.isEmpty(CallBackEntity.get(0).getFontColor())) {
                                tvOnPackageDetailOtherBox.setText(CallBackEntity.get(0).getResultInfo());
                                tvOnPackageDetailOtherBox.setTextColor(GetColorValue(CallBackEntity.get(0).getFontColor()));
                            } else {
                                //呼叫WMS
                                callWaitOut(CallBackEntity.get(0));
                            }
                        }

                    }
                    break;
                case MSG_waitOutCall:
                    waitoutWms(msg.obj.toString());
                    break;

                case MSG_ExceptionState:
                    if (ExceptionStateJsonArray != null && ExceptionStateJsonArray.length() > 0) {
                        Gson gson = new Gson();
                        List<CallBackEntity> bagCallWMSEntities = gson.fromJson(String.valueOf(ExceptionStateJsonArray), new TypeToken<List<CallBackEntity>>() {
                        }.getType());
                        if (bagCallWMSEntities != null && bagCallWMSEntities.size() > 0) {
                            showException(bagCallWMSEntities.get(0).getResultInfo());
                        }


                    }
                    break;
                case MSG_ALL_BOX_INFO:
                    if (ALLBoxInfoJsonarray != null && ALLBoxInfoJsonarray.length() > 0) {
                        Gson gson = new Gson();
                        List<AllBoxInfpEntity> bagCallWMSEntities = gson.fromJson(String.valueOf(ALLBoxInfoJsonarray), new TypeToken<List<AllBoxInfpEntity>>() {
                        }.getType());
                        if (bagCallWMSEntities != null && bagCallWMSEntities.size() > 0) {
                            tv_on_package_all_num_andout.setText("总箱数:" + bagCallWMSEntities.get(0).getSumBox() + "已出库:" + bagCallWMSEntities.get(0).getSumOutBox());
                        }
                    }
                    break;
                //获取明细
                case MSG_ALL_BOX_DETAIL_INFO:
                    if (ALLBoxDetailInfoJsonarray != null && ALLBoxDetailInfoJsonarray.length() > 0) {
                        Gson gson = new Gson();
                        List<BoxInfpEntity> bagCallWMSEntities = gson.fromJson(String.valueOf(ALLBoxDetailInfoJsonarray), new TypeToken<List<BoxInfpEntity>>() {
                        }.getType());
                        boxInfpEntityList.clear();
                        boxInfpEntityList.addAll(bagCallWMSEntities);
                        if (boxInfpEntityList != null && boxInfpEntityList.size() > 0) {
                            onPackageDetailBoxAdapter.notifyDataSetChanged();
                        }
                    }
                    break;
                default:
                    break;
            }
        }
    };



    private void getAllBoxInfo() {
        /**
         * --刷新 箱数
         * --EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='B00K00001',@WMSOrderNo ='',@DBHbw='D100320210308043-YC,1-印花',@TaskID ='32A97B45-7E7B-453E-BB6F-B61A20201915', @FormType='',@OperType='刷新总箱数',@UserNo='89898989'
         */

        String sql = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@WMSOrderNo ='',@DBHbw='',@TaskID ='" + TaskID + "', @FormType='" + FormType + "',@OperType='刷新总箱数',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sql, "MSG_ALL_BOX_INFO");

    }

    private void getAllBoxDetailInfo() {
        /**查询明细
         * --EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='B00K00001',@WMSOrderNo ='',@DBHbw='D100320210308043-YC,1-印花',@TaskID ='32A97B45-7E7B-453E-BB6F-B61A20201915', @FormType='',@OperType='查看明细',@UserNo='89898989'
         */

        String sql = "EXEC AGV_Check_CheckBagCallWMS @CurStationNo ='" + StationNo + "',@WMSOrderNo ='',@DBHbw='',@TaskID ='" + TaskID + "', @FormType='" + FormType + "',@OperType='查看明细',@UserNo='" + LoginUserNo + "'";
        ReadSQLData(sql, "MSG_ALL_BOX_DETAIL_INFO");
    }


    private void callWaitOut(OutStateEntity outStateEntity) {
        OutStateEntity outStateEntity1 = null;
        if (outStateEntity != null) {
            outStateEntity1 = new OutStateEntity(outStateEntity.getSiteNo(), outStateEntity.getOrderNo(), outStateEntity.getOrderOperate(), outStateEntity.getUserNo());
            String json = new Gson().toJson(outStateEntity1);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入WMS地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/OutTaskUpdate", json, handler, MSG_waitOutCall);
        }
    }


    private void instorecallWms(InstorCallWmsEntity instorCallWmsEntity) {
        if (instorCallWmsEntity != null) {
            InstorCallWmsEntity instore = new InstorCallWmsEntity(instorCallWmsEntity.getDepSiteNo(), instorCallWmsEntity.getDestSiteNo(), instorCallWmsEntity.getBoxNo()
                    , instorCallWmsEntity.getBoxType(), instorCallWmsEntity.getIsEmpty(), instorCallWmsEntity.getBoxHeight(), instorCallWmsEntity.getBoxVolume()
                    , instorCallWmsEntity.getUserNo(), instorCallWmsEntity.getBookNo(), instorCallWmsEntity.getDestOrderNo());
            String json = new Gson().toJson(instore);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入Agv地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/BoxPackage", json, handler, MSG_instoreCallWms_result);
        }
    }


    private void getPullAwayBusWMS(List<PullEmptyBueEntity> putWallEntities) {
        PullEmptyBueEntity pullEmptyBueEntity = null;
        if (putWallEntities != null && putWallEntities.size() > 0) {
            pullEmptyBueEntity = new PullEmptyBueEntity(putWallEntities.get(0).getSiteNo(), putWallEntities.get(0).getContent(), putWallEntities.get(0).getLineNo(), putWallEntities.get(0).getUserNo());
            String json = new Gson().toJson(pullEmptyBueEntity);
            if (MyApplication.UrlAgv.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入Agv地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlAgv + "/Piece/CallAgv", json, handler, MSG_PullAwayBusResult);
        }
    }


    private void getPullEmptyBusWMS(List<PullEmptyBueEntity> pullEmptyBueEntities) {
        PullEmptyBueEntity pullEmptyBueEntity = null;
        if (pullEmptyBueEntities != null && pullEmptyBueEntities.size() > 0) {
            pullEmptyBueEntity = new PullEmptyBueEntity(pullEmptyBueEntities.get(0).getSiteNo(), pullEmptyBueEntities.get(0).getUserNo());
            String json = new Gson().toJson(pullEmptyBueEntity);
            if (MyApplication.UrlAgv.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入Agv地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlAgv + "/Piece/CallEmpty", json, handler, MSG_PullEmptyBusResult);
        }
    }

    private void PickWall(List<PickWallEntity> check_checkBagCallWMSEntities) {
        PickWallEntity pickWallEntity = null;
        if (check_checkBagCallWMSEntities != null && check_checkBagCallWMSEntities.size() > 0) {
            pickWallEntity = new PickWallEntity(check_checkBagCallWMSEntities.get(0).getSiteNo(), check_checkBagCallWMSEntities.get(0).getCrossNo(), check_checkBagCallWMSEntities.get(0).getUserNo());
            String json = new Gson().toJson(pickWallEntity);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入WMS地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/PickWall", json, handler, MSG_PickWallResult);
        }
    }

    private void PutWall(List<PutWallEntity> check_checkBagCallWMSEntities) {
        System.out.println("PutWall:" + check_checkBagCallWMSEntities);
        PutWallEntity putWallEntity = null;
        if (check_checkBagCallWMSEntities != null && check_checkBagCallWMSEntities.size() > 0) {
            putWallEntity = new PutWallEntity(check_checkBagCallWMSEntities.get(0).getSiteNo(), check_checkBagCallWMSEntities.get(0).getPieceNo(), check_checkBagCallWMSEntities.get(0).getUserNo());
            String json = new Gson().toJson(putWallEntity);
            if (MyApplication.UrlWms.isEmpty()) {
                Toast.makeText(OnPackageDetailActivity.this, "请先输入WMS地址", Toast.LENGTH_LONG).show();
                return;
            }
            System.out.println(json);
            postJsonData(MyApplication.UrlWms + "/PutWall", json, handler, MSG_PutWallResult);
        }
    }



    //保留英文和数字
    private String dealCode(String code) {
        return code.replaceAll("[^a-zA-Z0-9$%]", "");
    }


    //列表点击状态的时候显示
    @Override
    public void OutState(int position) {
        if (onPackageDetailListEntities.get(position).getOutState().equals("待出库")) {
            showOutStateWait(onPackageDetailListEntities.get(position));
        } else if (onPackageDetailListEntities.get(position).getOutState().equals("异常")) {
            //showException(onPackageDetailListEntities.get(position));
            exceptionState(onPackageDetailListEntities.get(position));
        }
    }


    private void showChooseBox(String boxNo) {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_instore_type, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView tv_on_package_detail_empty = view.findViewById(R.id.tv_on_package_detail_empty);
        TextView tv_on_package_detail_contain_little = view.findViewById(R.id.tv_on_package_detail_contain_little);


        tv_on_package_detail_empty.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                instoreCallWms(boxNo, "1");
                popupWindow.dismiss();
            }
        });
        tv_on_package_detail_contain_little.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                instoreCallWms(boxNo, "0");
                popupWindow.dismiss();
            }
        });
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


    private void showException(String info) {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_exection, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView tv_exception = view.findViewById(R.id.tv_exception);
        tv_exception.setText(info);
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }

    private void showOutStateWait(OnPackageDetailListEntity onPackageDetailListEntity) {
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = windowManager.getDefaultDisplay().getWidth();
        View view = LayoutInflater.from(this).inflate(R.layout.popupwindow_out_state_wait, null);
        final PopupWindow popupWindow = new PopupWindow(view, width / 2, ViewGroup.LayoutParams.WRAP_CONTENT);
        ImageView back = view.findViewById(R.id.iv_out_bound_back);
        TextView wait_out = view.findViewById(R.id.tv_on_package_detail_empty);
        TextView out = view.findViewById(R.id.tv_on_package_detail_contain_little);


        //恢复出库
        out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Out(onPackageDetailListEntity);
                //popupWindow.dismiss();
            }
        });
        //暂停出库
        wait_out.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {


                waitOut(onPackageDetailListEntity);
                //popupWindow.dismiss();
            }
        });
        back.setOnClickListener(v -> {
            popupWindow.dismiss();
        });
        popupWindow.setFocusable(true);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);
    }


}